package com.alibobo.tech5.sixenine;

import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;

import com.alibobo.tech5.sixenine.internal.PanKey;
import com.alibobo.utils.file.FileUtils;
import com.alibobo.utils.json.JsonUtils;

public class GanJiResourceManager {

	Context _context = null;

	public GanJiResourceManager(Context ctx) {
		_context = ctx;
	}

	public void setContext(Context ctx) {
		_context = ctx;
	}

	protected String readResAsString(String fileName) throws IOException {
		InputStream in = _context.getResources().getAssets().open(fileName);
		if (in != null) {
			String r = FileUtils.readInputStreamAsString(in);
			in.close();
			return r;
		}
		return null;
	}

	JSONObject _panpool = null;

	protected JSONObject getShortPanPool() {
		if (_panpool == null) {
			String fileName = "pan.json";
			try {
				String content = readResAsString(fileName);
				JSONObject jObject = new JSONObject(content);
				_panpool = jObject;
			} catch (Exception e) {
			}
		}
		return _panpool;
	}

	public Hashtable<String, Object> getPanBy(String 日干支, int offset) {

		Hashtable<String, Object> rr = new Hashtable<String, Object>();
		JSONObject jObject = getShortPanPool();
		if (jObject == null)
			return rr;

		try {
			JSONArray ja = jObject.getJSONArray(日干支);
			int sz = ja.length();
			JSONObject target = null;
			for (int i = 0; i < sz; i++) {
				JSONObject item = ja.getJSONObject(i);
				int off = item.getInt("o");
				if (offset == off) {
					target = item;
					break;
				}
			}

			rr.put(PanKey.日干支, 日干支);
			rr.put(PanKey.panOffset, target.getInt("o"));
			rr.put(PanKey.干上, target.getString("up"));
			rr.put(PanKey.發用課, target.getInt("pick"));
			rr.put(PanKey.三傳, target.getString("t3"));
			rr.put(PanKey.日空, target.getString("empty"));
			// rr.put("tm", target.getString("��O"));
			rr.put(PanKey.notes, target.getString("notes"));
			rr.put(PanKey.日貴,
					JsonUtils.readStringArrayFrom(target.getJSONArray("day")));
			rr.put(PanKey.夜貴,
					JsonUtils.readStringArrayFrom(target.getJSONArray("night")));
		} catch (Exception e) {
			e.printStackTrace();

		}
		return rr;
	}

}
